package com.bac.rentmap.ad.flat.security.jdo;

import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.beans.factory.annotation.Required;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.image.JdoFlatImageService;
import com.bac.rentmap.ad.flat.security.FlatDao;
import com.bac.rentmap.jdo.JdoSupport;

public class JdoFlatDao extends JdoSupport implements FlatDao {
    private static final Logger log = Logger.getLogger(JdoFlatDao.class
            .getName());
    private JdoFlatImageService flatImageService;

    @Override
    public Object getBySecureId(Class<?> clazz, String secureId) {
        log.fine("Loading flat " + clazz + " by secureId: '" + secureId + "'");
        PersistenceManager persistenceManager = getPersistenceManager();
        try {
            return getBySecureId(clazz, secureId, persistenceManager);
        } finally {
            persistenceManager.close();
        }
    }

    public Object getBySecureId(Class<?> clazz, String secureId,
            PersistenceManager persistenceManager) {
        Query query = persistenceManager.newQuery(clazz);
        query.setFilter("secureId == secureIdParam");
        query.declareParameters("String secureIdParam");
        query.setUnique(true);

        return query.execute(secureId);
    }

    @Override
    public Long deleteBySecureId(String secureId,
            PersistenceManager persistenceManager) {
        log.fine("Deleting flat by secureId: '" + secureId + "'");

        FlatAd flatAd = (FlatAd) getBySecureId(FlatAd.class, secureId,
                persistenceManager);
        if (flatAd == null)
            return null;
        flatImageService.deleteAll(flatAd.getId(), persistenceManager);
        persistenceManager.deletePersistent(flatAd);
        return flatAd.getId();
    }

    @Required
    public void setFlatImageService(JdoFlatImageService flatImageService) {
        this.flatImageService = flatImageService;
    }
}
